//
//  HExamContentViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/9/25.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HExamContentViewController.h"

#import "HChooseBankViewController.h"
#import "DIHTest.h"
#import "HAnswerTableViewCell.h"
#import "HExamHeadView.h"
#import "HtestCollectionViewCell.h"
#import "SizeToFit.h"
#import <TMCache.h>

#import "HSingleSeletView.h"
#import "HMultiSelectView.h"
#import "UIButton+BackgroundColor.h"

#import "Header.h"
#import "HCommon.h"

#import "HShowALLQuesView.h"
#import "Model_Hr_ExamContent.h"
#import "Networking.h"

#import <MSWeakTimer.h>
#import "FLCountDownView.h"
#import "Model_Hr_Exam_Primary.h"
#import "InitDbTableExamOnLine.h"
#import "UserDefault.h"
#import "ModelToJson.h"
@interface HExamContentViewController () <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>




@property (strong, nonatomic) UICollectionViewFlowLayout *collectionViewLayout;

@property (strong, nonatomic) UICollectionView           *collectionView;

//数据源
@property (strong, nonatomic) NSMutableArray             *dataSource;
//答案
@property (strong, nonatomic) NSMutableArray             *resultArray;

@property (strong, nonatomic) NSMutableArray             *indexPathArray;
//当前选中的item
@property (assign, nonatomic) NSInteger                   currentSelectIndex;

@property (nonatomic, strong) NSMutableArray *array;

@property (nonatomic, strong) UIButton *button;

@property (nonatomic, copy) NSString *exam_id;

@property (nonatomic, strong)UILabel *timeLabel;

@property (nonatomic, strong)NSMutableArray *onLineArray;

@property (nonatomic, copy) NSString *nowTime;

@property (nonatomic, copy) NSString *res_id;

@property (nonatomic, assign) NSInteger result_flag;

@property (nonatomic, assign) NSInteger record_flag;

@property (nonatomic, assign) NSInteger type;

@property (nonatomic, strong) NSMutableArray *examDetailArray;

@property (nonatomic, assign) BOOL upload;
@end

@implementation HExamContentViewController

- (instancetype)initWithDataArray:(NSString *)exam_id
                           res_id:(NSString *)res_id
                      result_flag:(NSInteger)result_flag
                      record_flag:(NSInteger)record_flag
                             type:(NSInteger)type{
    if (self) {
        self.exam_id = exam_id;
        self.array = [NSMutableArray new];
        self.res_id = res_id;
        self.dataSource = [NSMutableArray new];
        self.onLineArray = [NSMutableArray new];
        self.examDetailArray = [NSMutableArray new];
        self.record_flag = record_flag;
        self.result_flag = result_flag;
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.upload = 0;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.nowTime =  [[HBaseViewController alloc]getNowDate];
    
    [self getExamContentWithExamID:self.exam_id];
    
    UIBarButtonItem *execbtn = [[UIBarButtonItem alloc] initWithTitle:@"提交试卷" style:UIBarButtonItemStylePlain target:self action:@selector(didDeleteButttonClicked:)];
    
    self.navigationItem.rightBarButtonItem = execbtn;
    
    self.navigationItem.titleView = nil;
    
    [self timeCountDown];
    
    [self initView];
    

}

- (void)timeCountDown {
    
    FLCountDownView *countDown      = [FLCountDownView fl_countDown];
    
    countDown.frame                 = CGRectMake(100, 100, 100, 50);
    
    countDown.timestamp             = [self.time integerValue] * 60;
    
    
    typeof(FLCountDownView*) weakAlertView = countDown;
    
    
    countDown.timerStopBlock = ^{
        
        HBaseViewController *hbase = [[HBaseViewController alloc]init];
        Model_Hr_Exam_Primary *PrimaryModel = [[Model_Hr_Exam_Primary alloc]init];
        PrimaryModel.RES_ID = self.res_id;
        PrimaryModel.EXP_ID = self.exam_id;
        PrimaryModel.EMP_ID = UserDefault.getUserInfo.EMP_ID;
        PrimaryModel.EMP_CODE = UserDefault.getUserInfo.USER_CODE;
        PrimaryModel.EMP_NAME = UserDefault.getUserInfo.USER_NAME;
        PrimaryModel.SUB_TIME = [hbase getNowDate];
        InitDbTableExamOnLine *line = [[InitDbTableExamOnLine alloc]init];
        NSArray *scoreArray = [line getDetailWithRight:self.res_id];
        int score  = 0;
        for (Model_Hr_ExamAnswer *model in scoreArray) {
            
            if (model.QUES_SCORE == nil) {
                
                model.QUES_SCORE = 0;
            }
            score = score + model.QUES_SCORE;
        }
        
        PrimaryModel.RESULT = [NSString stringWithFormat:@"%d",score];
        PrimaryModel.START_TIME = self.nowTime;
        PrimaryModel.USETIMES = [hbase getTotalTimeWithStartTime:self.nowTime endTime:PrimaryModel.SUB_TIME];
        PrimaryModel.SCORE = [NSString stringWithFormat:@"%ld",self.score_count];
        PrimaryModel.MARKUP_FLAG = 0;
        PrimaryModel.HASMARKUP = 0;
        PrimaryModel.TEMP_FLAG = 0;
        PrimaryModel.MARKUP_SCORE = 0;
        PrimaryModel.DEPT_ID = @"";
        PrimaryModel.DEPT_NAME = @"";
        PrimaryModel.ORG_ID = @"";
        PrimaryModel.IPS = @"";
        PrimaryModel.title = self.title;
        
        [line primary:PrimaryModel];
        
        NSMutableArray *array = [line GetPrimaryUnUploadTableWithResid:self.res_id];
        
        NSMutableArray *dataArray =[line GetDetailIUnUploadTableWithResid:self.res_id];
        
        NSString *jsonText = [ModelToJson toJSON:array options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *jsonTextDetail = [ModelToJson toJSON:dataArray options:NSJSONWritingPrettyPrinted error:nil];
        
        
        
        [line startUpload:jsonText inspect_detail:jsonTextDetail block:^(NSDictionary *param){
            
            BOOL flag =  [[param valueForKey:@"flag"] boolValue];
            if( flag ){
                
                [HCommon popupSuccessMessage:@"上传成功"];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            NSString *msg = (NSString*)[param objectForKey: @"msg" ];
            [self alert:msg];
        }];
        
        
        
    };
    countDown.timerWithFive = ^{
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"还剩5分钟,请注意!"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 200;
        alert.delegate = self;
        
        
        weakAlertView.minuesLabel.textColor = [UIColor redColor];
        
        weakAlertView.secondsLabel.textColor = [UIColor redColor];
        
        
    };
    
    self.navigationItem.titleView = countDown;


}

- (void)getExamContentWithExamID:(NSString *)examID{
    
    [HCommon popupMessage:@"正在生成试卷,请稍后"];
    NSString *url = AppServiceConfig.GetServiceUrl;
        
    NSString *downUrl  = [NSString stringWithFormat:@"%@/%@?token=%@&exp_id=%@",url,@"GetExamPaperContent",[[TMCache sharedCache] objectForKey:@"deviceToken"],examID];
    
    [Networking receiveDataWithURLString:downUrl method:@"GET" body:nil Block:^(NSData *tempData) {
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:tempData options:NSJSONReadingMutableContainers error:nil];
        
        BOOL flag = [dic valueForKey:@"flag"];
    
        if (flag) {
            
            [HCommon dismissAnimated:YES];
 
        }
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        
        NSArray *examPaperArray = [dataDic objectForKey:@"data_exam_paper"];
        
        for (NSDictionary *paperDic in examPaperArray) {
            
            Model_Hr_Question_Item *modelOnLine = [[Model_Hr_Question_Item alloc]initWithDictionary:paperDic];
            
            
            [self.dataSource addObject:modelOnLine];
            
            [self.collectionView reloadData];
        }
        
        NSMutableArray *answerArray = [NSMutableArray new];
        
        for (int i = 0; i < self.dataSource.count; i++) {
            
            Model_Hr_Question_Item *iteModel = self.dataSource[i];
            
            Model_Hr_ExamAnswer *model = [[Model_Hr_ExamAnswer alloc]init];
            
            model.QUES_ID = iteModel.QUES_ID;
            
            model.TYPEID = iteModel.TYPEID;
            
            model.TITLE = iteModel.TITLE;
            
            model.ANSWER = iteModel.ANSWER;
            
            model.ANSWER_FLAG = [iteModel.ANSWER_FLAG integerValue];
            
            model.OPTION1 = iteModel.OPTION1;
            
            model.OPTION2 = iteModel.OPTION2;
            model.OPTION3 = iteModel.OPTION3;
            model.OPTION4 = iteModel.OPTION4;
            model.OPTION5 = iteModel.OPTION5;
            model.OPTION6 = iteModel.OPTION6;
            model.OPTION7 = iteModel.OPTION7;
            model.OPTION8 = iteModel.OPTION8;
            model.OPTION9 = iteModel.OPTION9;
            model.OPTION10 = iteModel.OPTION10;

            model.ORDER_NUM = iteModel.ORDER_NUM;
            
            model.THOUGHTS = iteModel.THOUGHTS;
            
            model.RES_ID = self.res_id;
            
            [answerArray addObject:model];
            
        }
        
        InitDbTableExamOnLine *line = [[InitDbTableExamOnLine alloc]init];
        
        [line insetInDetail:answerArray];
        
        self.examDetailArray = [line GetDetailIUnUploadTableWithResid:self.res_id];
        
        
        for (Model_Hr_Question_Item *model in self.dataSource) {
            
            model.answers = nil;
        }
        
    }];
}




- (void)didDeleteButttonClicked:(UIButton *)sender {
    
    InitDbTableExamOnLine *line = [[InitDbTableExamOnLine alloc]init];
    NSMutableArray *unAnswer = [NSMutableArray new];
    unAnswer = [line unAnswerQuesWithRes_id:self.res_id];

    if (unAnswer.count > 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"您还有%ld题未做,确定交卷吗?",unAnswer.count]
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 300;
        alert.delegate = self;

    }else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确定提交试卷?"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 300;
        alert.delegate = self;


    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 300) {
        switch (buttonIndex) {
            case 0:{
                return;
            }
                break;
            case 1:{
                HBaseViewController *hbase = [[HBaseViewController alloc]init];
                Model_Hr_Exam_Primary *PrimaryModel = [[Model_Hr_Exam_Primary alloc]init];
                PrimaryModel.RES_ID = self.res_id;
                PrimaryModel.EXP_ID = self.exam_id;
                PrimaryModel.EMP_ID = UserDefault.getUserInfo.EMP_ID;
                PrimaryModel.EMP_CODE = UserDefault.getUserInfo.USER_CODE;
                PrimaryModel.EMP_NAME = UserDefault.getUserInfo.USER_NAME;
                PrimaryModel.SUB_TIME = [hbase getNowDate];
                InitDbTableExamOnLine *line = [[InitDbTableExamOnLine alloc]init];
                NSArray *scoreArray = [line getDetailWithRight:self.res_id];
                int score  = 0;
                for (Model_Hr_ExamAnswer *model in scoreArray) {
                    
                    score = score + model.QUES_SCORE;
                }
                PrimaryModel.SCORE = [NSString stringWithFormat:@"%d",score];
                PrimaryModel.START_TIME = self.nowTime;
                PrimaryModel.USETIMES = [hbase getTotalTimeWithStartTime:self.nowTime endTime:PrimaryModel.SUB_TIME];
                PrimaryModel.RESULT = [NSString stringWithFormat:@"%ld",self.score_count];
                PrimaryModel.MARKUP_FLAG = 0;
                PrimaryModel.HASMARKUP = 0;
                PrimaryModel.TEMP_FLAG = 0;
                PrimaryModel.MARKUP_SCORE = 0;
                PrimaryModel.DEPT_ID = @"";
                PrimaryModel.DEPT_NAME = @"";
                PrimaryModel.ORG_ID = @"";
                PrimaryModel.IPS = @"";
                PrimaryModel.title = self.title;
                
                
                
                    [line primary:PrimaryModel];
                    
                    NSMutableArray *array = [line GetPrimaryUnUploadTableWithResid:self.res_id];
                    
                    NSMutableArray *dataArray =[line GetDetailIUnUploadTableWithResid:self.res_id];
                    
                    NSString *jsonText = [ModelToJson toJSON:array options:NSJSONWritingPrettyPrinted error:nil];
                    
                    NSString *jsonTextDetail = [ModelToJson toJSON:dataArray options:NSJSONWritingPrettyPrinted error:nil];
                
                //标识主表Resid唯一
                    if (array.count == 1) {
                        
                    [line startUpload:jsonText inspect_detail:jsonTextDetail block:^(NSDictionary *param){
                        
                    BOOL flag =  [[param valueForKey:@"flag"] boolValue];
                    NSString *msg = (NSString*)[param objectForKey: @"msg" ];
                        
                    if( flag ){
                        
                    self.upload = 1;
                        
                    if (self.result_flag == 1) {
                        
                    [self alert:[NSString stringWithFormat:@"您本次考试得分:%@分",PrimaryModel.SCORE]];
                        
                        
                        
                    }else {
                         
                    [HCommon popupSuccessMessage:msg];
                        
                        }
                        
                        
                    [self.navigationController popViewControllerAnimated:YES];
                                                    
                    NSNotification * notice = [NSNotification notificationWithName:@"examUploadSuccess" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter]postNotification:notice];
                        
                                                    
                    }else {
                                                    
                                                    
                    [self alert:msg];
                        
                        }
                        
                    }];
                }

            }
                break;
            default:
                break;
        }
    }
    
        if (alertView.tag == 200) {
            switch (buttonIndex) {
                case 0:{
                    return;
                }
                default:
                    break;
        }
    }
}


- (void)initView {
    
    
    
    [self.view addSubview:self.collectionView];
    
    
}

- (void)initData {
    
    [self dataSource];
    [self resultArray];
    [self indexPathArray];
    
    
    for (int i = 0; i < _dataSource.count; i++) {
        
        [_resultArray addObject:@[]];
        [_indexPathArray addObject:@[]];
    }
}
// 设置单元格的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

// 设置段数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    
    if (cell) {
        
        for (UIView *view in cell.contentView.subviews) {
            
            if (view) {
                
                [view removeFromSuperview];
            }
        }
    }
    Model_Hr_Question_Item *model = self.dataSource [indexPath.row];
    
    if ([model.TYPEID isEqualToString:@"1"] || [model.TYPEID isEqualToString:@"3"] || [model.TYPEID isEqualToString:@"4"]) {
        
        NSString *string  = [NSString stringWithFormat:@"%@",model.TITLE];
        CGFloat height = [SizeToFit getHeightByWidth:ScreenWidth - 20 title:string font:[UIFont systemFontOfSize:19]];
        
        
        __weak typeof(self) weakSelf = self;
        
        HSingleSeletView *singleView = [[HSingleSeletView alloc]initWithconfigure:indexPath.row dataArray:self.dataSource headHeight:height + 20 headTitle:string typeid:model.TYPEID onlineArray:self.onLineArray res_id:self.res_id FromType:0 examDetail:self.examDetailArray];
        
        singleView.frame = cell.contentView.bounds;
        [cell.contentView addSubview:singleView];
        
        
        singleView.SingleSelectBlock = ^(NSIndexPath *seleIndexPath, NSInteger btnTag ,BOOL isright ,NSInteger state) {
            
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (indexPath.item+1<self.dataSource.count) {
                if (state == 1 ) {
                    [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.item + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                }else {
                    [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:btnTag inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                }
                
            }else {
                [HCommon popupErrorMessage:@"已经是最后一题了"];
            }
        };
        
    }else {
        
        NSString *string  = [NSString stringWithFormat:@"%@",model.TITLE];
        CGFloat height = [SizeToFit getHeightByWidth:ScreenWidth - 20 title:string font:[UIFont systemFontOfSize:19]];
        
        HMultiSelectView *multiView = [[HMultiSelectView alloc]initWithconfigure:indexPath.row dataArray:self.dataSource headHeight:height + 20 headTitle:string typeid:model.TYPEID onlineArra:self.onLineArray res_id:self.res_id examDetail:self.examDetailArray];
        multiView.frame = cell.contentView.bounds;
        
        [cell.contentView addSubview:multiView];
        
        __weak typeof(self) weakSelf = self;
        
        multiView.MultiSelectBlock = ^(NSMutableArray * btnTagSum,NSInteger state,NSInteger rows) {
            
            if (indexPath.item+1<self.dataSource.count) {
                if (state == 1) {
                    [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.item + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                }else {
                    [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:rows inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                }
                
            }else {
                
                [HCommon popupErrorMessage:@"已经是最后一题了"];
            }
            
        };
    }
    return cell;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    [self scrollViewEndScrolling:scrollView.contentOffset];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    [self scrollViewEndScrolling:scrollView.contentOffset];
    
}

// 设置单元格大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(ScreenWidth, ScreenHeight - 64 );
}

// cell与cell之间的间隔，边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    //上左下右
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

// 设置垂直最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;
}

// 设置水平最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;
}

// 设置标题头大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(0, 0);
}

- (void)scrollViewEndScrolling:(CGPoint)contentOffset {
    
    NSInteger index = contentOffset.x / ScreenWidth;
    
    
    
    _currentSelectIndex = index;
}

//上一题下一题
- (void)collectionViewScrollToItem:(BOOL)bl btnTag:(NSInteger)btnTag {
    
    
    
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentSelectIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionViewLayout                          = [[UICollectionViewFlowLayout alloc] init]; // 自定义的布局对象
        _collectionView                                = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 , ScreenWidth, ScreenHeight - 64 ) collectionViewLayout:_collectionViewLayout];
        //移动方向
        _collectionViewLayout.scrollDirection          = UICollectionViewScrollDirectionHorizontal;
        //是否显示
        _collectionView.showsHorizontalScrollIndicator = NO;
        //是否有反弹效果
        _collectionView.bounces                        = YES;
        //是否整页翻页
        _collectionView.pagingEnabled                  = YES;
        //数据源代理
        _collectionView.dataSource                     = self;
        _collectionView.delegate                       = self;
        //滚动返回至顶部
        _collectionView.scrollsToTop                   = NO;
        _collectionView.backgroundColor                = [UIColor whiteColor];
        // 注册cell
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    }
    return _collectionView;
}



- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (NSMutableArray *)resultArray {
    if (!_resultArray) {
        _resultArray = [[NSMutableArray alloc]init];
    }
    return _resultArray;
}

- (NSMutableArray *)indexPathArray {
    if (!_indexPathArray) {
        _indexPathArray = [[NSMutableArray alloc]init];
    }
    return _indexPathArray;
}


- (void)viewDidDisappear:(BOOL)animated {
    
    if (self.upload == 0) {
        
        InitDbTableExamOnLine *online = [[InitDbTableExamOnLine alloc]init];
        
        [online deleteDetail:self.res_id];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
